package com.suwish.pc.ui.util;

import java.awt.Component;
import java.awt.Desktop;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.net.URI;

import javax.swing.AbstractAction;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;

import com.android.ddmlib.AdbCommandRejectedException;
import com.android.ddmlib.FileListingService.FileEntry;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.ShellCommandUnresponsiveException;
import com.android.ddmlib.TimeoutException;
import com.suwish.device.util.DeviceUtils;
import com.suwish.pc.Setting;
import com.suwish.pc.ui.component.KeyValueItem;
import com.suwish.pc.ui.dialog.ApkDetailDialog;
import com.suwish.pc.ui.main.MainFrame;
import com.suwish.pc.util.StringUtils;

/**
 * 
 * @author Min
 *
 */
public final class UIHelper {

	public static final String ACTION_FILE_UPLOAD = "file.upload";
	public static final String ACTION_FILE_DOWNLOAD = "file.download";
	public static final String ACTION_FOLDER_OPEN = "folder.open";
	
	private UIHelper(){}
	/**
	 * 
	 * 意义不大，即将取消。
	 * 
	 * @return
	 */
	public static JMenu getLookAndFeelMenu(){
		JMenu menu = new JMenu("Look&Feel");
		AbstractAction themeChangeAction = new AbstractAction() {
			private static final long serialVersionUID = 1L;
			@Override
			public void actionPerformed(ActionEvent e) {
				if(!(e.getSource() instanceof JMenuItem)) return;
				JMenuItem item = (JMenuItem)e.getSource();
				try{
//					System.err.println(item.getActionCommand());
//					UIManager.setLookAndFeel(item.getActionCommand());
				}catch(Exception ex){
					ex.printStackTrace();
				}
			}
		};		
		JMenuItem themeItem = null;
		for(LookAndFeelInfo lookAndFeel : UIManager.getInstalledLookAndFeels()){
			themeItem = new JMenuItem(lookAndFeel.getName());
			themeItem.addActionListener(themeChangeAction);
			themeItem.setActionCommand(lookAndFeel.getClassName());
			menu.add(themeItem);
		}
		if(menu.getSubElements().length > 0) menu.addSeparator();
		JMenuItem crossPlatformItem = new JMenuItem("CrossPlatform");
		crossPlatformItem.setActionCommand(UIManager.getCrossPlatformLookAndFeelClassName());
		crossPlatformItem.addActionListener(themeChangeAction);
		menu.add(crossPlatformItem);
		JMenuItem systemItem = new JMenuItem("System L&F");
		systemItem.setActionCommand(UIManager.getSystemLookAndFeelClassName());
		systemItem.addActionListener(themeChangeAction);
		menu.add(systemItem);
		return menu;
	}
	
	public static void viewApkDetail(Window parent){
		JFileChooser chooser = new JFileChooser();
		int result = chooser.showOpenDialog(MainFrame.getInstance());
		if(result == JFileChooser.CANCEL_OPTION) return;
		new ApkDetailDialog(parent, chooser.getSelectedFile().getAbsolutePath()).setVisible(true);
	}
	public static void showErrorDialog(Exception ex){
		showMessageDialog(MainFrame.getInstance(), ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
	}
	public static void showErrorDialog(Component parent , Exception ex){
		showMessageDialog(parent, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
	}
	public static void showErrorDialog(Component parent , String message){
		showMessageDialog(parent, message, "Error", JOptionPane.ERROR_MESSAGE);
	}
	public static void showMessageDialog(Component parent , String message, String title, int messageType){
		JOptionPane.showMessageDialog(parent, message, title, messageType);
	}
	public static void showMessageDialog(String message){
		showMessageDialog(MainFrame.getInstance(), message, "Message", JOptionPane.INFORMATION_MESSAGE);
		
	}
	
	
	public static int showFormatMessage(Component parent , String message, String title, int messageType){
		String show = "<html><table width='300px'><tr><td>" + message + "</td></tr></table></html>";
		return JOptionPane.showConfirmDialog(parent, show, title, messageType);
	}
	public static int getKeyValueItemIndex(JComboBox comboBox, String value){
		if(value == null) return -1;
		int count = comboBox.getItemCount();
		if(count == 0 || !(comboBox.getItemAt(0) instanceof KeyValueItem)) return -1;
		for(int index = 0 ; index < count ; index ++){
			KeyValueItem item = (KeyValueItem)comboBox.getItemAt(index);
			if(value.equals(item.getValue())) return index;
		}
		return -1;
	}
	
	public static void saveScreenshot(IDevice device){
		JFileChooser chooser = new JFileChooser();
		String fileName = "jpb-" + System.currentTimeMillis() + ".png";
		chooser.setSelectedFile(new File(fileName));
		int result = chooser.showSaveDialog(MainFrame.getInstance());
		if(result == JFileChooser.CANCEL_OPTION) return;
		try{
			DeviceUtils.saveScreenshot(device, chooser.getSelectedFile());
			showMessageDialog("Screenshot Success!\n" + chooser.getSelectedFile().getAbsolutePath());
		}catch(Exception ex){
			ex.printStackTrace();
			showErrorDialog(ex);
		}
	}
	
	/**
	 * 上传文件到制定目录
	 * 
	 * 
	 * @param device
	 * @param entry
	 * @throws SyncException
	 * @throws TimeoutException
	 * @throws AdbCommandRejectedException
	 * @throws IOException
	 */
	public static void uploadFile(IDevice device, FileEntry entry) 
				throws TimeoutException, AdbCommandRejectedException, IOException{
		JFileChooser chooser = new JFileChooser();
		int result = chooser.showOpenDialog(MainFrame.getInstance());
		if(result == JFileChooser.CANCEL_OPTION) return;		
		DeviceUtils.pushFile(device, new String[]{ chooser.getSelectedFile().getAbsolutePath()}, entry);
	}
	/**
	 * 
	 * 下载文件到目录
	 * 
	 * @param device
	 * @param entry
	 * @throws SyncException
	 * @throws TimeoutException
	 * @throws AdbCommandRejectedException
	 * @throws IOException
	 */
	public static void downloadFile(IDevice device, FileEntry entry) 
				throws TimeoutException, AdbCommandRejectedException, IOException{
		JFileChooser chooser = new JFileChooser();
		chooser.setSelectedFile(new File(entry.getName()));
		int result = chooser.showSaveDialog(MainFrame.getInstance());
		if(result == JFileChooser.CANCEL_OPTION) return;
		DeviceUtils.pullFile(device, entry, chooser.getSelectedFile().getAbsolutePath());
	}
	public static void uninstallApk(IDevice device) 
		throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException, IOException{
		String packageName = getInputValue("Input package name");
		if(StringUtils.isEmpty(packageName)) return;
		DeviceUtils.uninstallAPK(device, packageName);
	}
	public static String getInputValue(String value){
		return JOptionPane.showInputDialog(MainFrame.getInstance(), StringUtils.isEmpty(value) ? "Input" : value,
				"Option", JOptionPane.QUESTION_MESSAGE);
	}
	
	public static void openSupportWebsite(){
		try{
			openWebSite(Setting.get("support.site"));
		}catch(Exception ex){
			showErrorDialog(ex);
		}
	}
	
	public static void openWebSite(String url) throws IOException{
		if(!Desktop.isDesktopSupported()) return;
		Desktop desktop = Desktop.getDesktop();
		if(!desktop.isSupported(Desktop.Action.BROWSE))return;
		desktop.browse(URI.create(url));
	}
}
